<script lang="ts" setup name="RegisterForm">
import type { FormRules } from 'element-plus'
import { setTenantIdCache } from '@/utils/auth'
import { useIcon } from '@/hooks/web/useIcon'
import { useForm } from '@/hooks/web/useForm'
import { useValidator } from '@/hooks/web/useValidator'
import LoginFormTitle from './LoginFormTitle.vue'
import { LoginStateEnum, useLoginState } from './useLogin'
import { AuthApi } from '@/api/auth'

const { t } = useI18n()
const message = useMessage()
const iconHouse = useIcon({ icon: 'ep:house' })
const iconAvatar = useIcon({ icon: 'ep:avatar' })
const iconCellphone = useIcon({ icon: 'ep:cellphone' })
const iconLock = useIcon({ icon: 'ep:lock' })
const iconCircleCheck = useIcon({ icon: 'ep:circle-check' })
const { required } = useValidator()
const { elFormRef } = useForm()
const { handleBackLogin, getLoginState } = useLoginState()
const getShow = computed(() => unref(getLoginState) === LoginStateEnum.REGISTER)

const rules: FormRules = {
  tenantName: [required()],
  username: [required()],
  mobileNumber: [required()],
  password: [required()],
  check_password: [required()],
  code: [required()]
}

const registerData = reactive({
  tenantEnable: import.meta.env.VITE_APP_TENANT_ENABLE,
  registerForm: {
    tenantName: import.meta.env.VITE_APP_DEFAULT_LOGIN_TENANT || '',
    username: '',
    mobileNumber: '',
    code: '',
    password: '',
    check_password: ''
  }
})

const smsInfo = reactive({
  smsCode: {
    mobile: '',
    scene: 21
  }
})

const mobileCodeTimer = ref(0)
const getSmsCode = async () => {
  await getTenantId()
  smsInfo.smsCode.mobile = registerData.registerForm.mobileNumber
  await AuthApi.Sms.code(smsInfo.smsCode).then(async () => {
    message.success(t('sign.fields.code', 'send'))
    // 设置倒计时
    mobileCodeTimer.value = 60
    let msgTimer = setInterval(() => {
      mobileCodeTimer.value = mobileCodeTimer.value - 1
      if (mobileCodeTimer.value <= 0) {
        clearInterval(msgTimer)
      }
    }, 1000)
  })
}

// 获取租户 ID
const getTenantId = async () => {
  if (registerData.tenantEnable === 'true') {
    const res = await AuthApi.Tenant.getIdByName(registerData.registerForm.tenantName)
    setTenantIdCache(res)
  }
}

const loading = ref(false)

const loginRegister = async () => {
  const formRef = unref(elFormRef)
  formRef?.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
      } finally {
        loading.value = false
      }
    }
  })
}
</script>

<template>
  <el-form v-show="getShow" ref="formSmsLogin" :model="registerData.registerForm" :rules="rules" class="login-form" label-position="top" label-width="120px" size="large">
    <el-row>
      <el-col :span="24">
        <el-form-item>
          <LoginFormTitle style="width: 100%" />
        </el-form-item>
      </el-col>
      <!-- 租户名 -->
      <el-col :span="24">
        <el-form-item v-if="registerData.tenantEnable === 'true'" prop="tenantName">
          <el-input v-model="registerData.registerForm.tenantName" :placeholder="t('sign.fields.tenant', 'placeholder')" :prefix-icon="iconHouse" type="primary" link />
        </el-form-item>
      </el-col>
      <!-- 用户名 -->
      <el-col :span="24" class="mt-[12px]">
        <el-form-item prop="username">
          <el-input v-model="registerData.registerForm.username" :placeholder="t('sign.fields.username', 'placeholder')" :prefix-icon="iconAvatar" />
        </el-form-item>
      </el-col>
      <!-- 手机号 -->
      <el-col :span="24" class="mt-[12px]">
        <el-form-item prop="mobileNumber">
          <el-input v-model="registerData.registerForm.mobileNumber" :placeholder="t('sign.fields.mobile', 'placeholder')" :prefix-icon="iconCellphone" />
        </el-form-item>
      </el-col>
      <!-- 验证码 -->
      <el-col :span="24" class="mt-[12px]">
        <el-form-item prop="code">
          <el-input v-model="registerData.registerForm.code" :placeholder="t('sign.fields.code', 'placeholder')" :prefix-icon="iconCircleCheck">
            <template #append>
              <span v-if="mobileCodeTimer <= 0" class="getMobileCode" style="cursor: pointer" @click="getSmsCode">
                {{ t('sign.fields.code', 'button') }}
              </span>
              <span v-if="mobileCodeTimer > 0" class="getMobileCode" style="cursor: pointer">
                {{ t('sign.fields.code', 'restart', [mobileCodeTimer]) }}
              </span>
            </template>
          </el-input>
        </el-form-item>
      </el-col>
      <!-- 新密码 -->
      <el-col :span="24" class="mt-[12px]">
        <el-form-item prop="password">
          <InputPassword v-model="registerData.registerForm.password" :placeholder="t('sign.fields.password', 'placeholder')" :prefix-icon="iconLock" strength style="width: 100%;" />
        </el-form-item>
      </el-col>
      <!-- 确认密码 -->
      <el-col :span="24" class="mt-[12px]">
        <el-form-item prop="check_password">
          <InputPassword v-model="registerData.registerForm.check_password" :placeholder="t('sign.fields.password', 'placeholderTwice')" :prefix-icon="iconLock" strength style="width: 100%;" />
        </el-form-item>
      </el-col>
      <!-- 注册按钮 / 返回按钮 -->
      <el-col :span="24" class="mt-[12px]">
        <el-form-item>
          <CButton :loading="loading" :title="t('sign.register', 'action')" class="w-[100%]" type="primary" @click="loginRegister()" />
        </el-form-item>
      </el-col>
      <el-col :span="24" class="mt-[12px]">
        <el-form-item>
          <CButton :title="t('sign', 'hasUser')" class="other-button w-[100%]" @click="handleBackLogin()" />
        </el-form-item>
      </el-col>
    </el-row>
  </el-form>
</template>
